package niit.wei.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author WeiJinLong
 * @Date 2023-06-29 10:34
 * @Version 1.0
 */
public class JdbcUtil {


    public static ThreadLocal<Connection> pool = new ThreadLocal<Connection>();
     public static Properties properties = null;
    static {
        InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties = new Properties();
            properties.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static Connection getConnection()  {
        Connection conn = pool.get();
        if (conn == null){
            try {
                conn = DriverManager.getConnection(properties.getProperty("jdbc_url"), properties.getProperty("jdbc_user"),
                        properties.getProperty("jdbc_password"));
                return conn;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return conn;
    }
    public static void close(){
        Connection conn = pool.get();
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
